package com.sk.cardeal.act.home.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.R;
import com.sk.cardeal.adapter.FixingOtherPayAdapter;
import com.sk.cardeal.adapter.FixingPartsAdapter;
import com.sk.cardeal.adapter.FixingProjectAdapter;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.entity.ByPartsList;
import com.sk.cardeal.entity.CostType;
import com.sk.cardeal.entity.NewPartsList;
import com.sk.cardeal.entity.Parts;
import com.sk.cardeal.entity.Project;
import com.sk.cardeal.entity.WorkFormDetails;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.view.IconViewTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by sk on 2018/1/30.
 */

@RuntimePermissions
public class StateQualifiedActivity extends BaseActivity implements HandleDataCallBack {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.share)
    TextView share;
    @BindView(R.id.tv_state)
    TextView tvState;
    @BindView(R.id.order_num)
    TextView orderNum;
    @BindView(R.id.car_num)
    TextView carNum;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.phone_icon)
    ImageView phoneIcon;
    @BindView(R.id.tip_type)
    TextView tipType;
    @BindView(R.id.car_type)
    TextView carType;
    @BindView(R.id.tv_owner)
    TextView tvOwner;
    @BindView(R.id.in_time)
    TextView inTime;
    @BindView(R.id.fix_type)
    TextView fixType;
    @BindView(R.id.main_pep)
    TextView mainPep;
    @BindView(R.id.tech_pep)
    TextView techPep;
    @BindView(R.id.repair_tips)
    TextView repairTips;
    @BindView(R.id.project)
    IconViewTextView project;
    @BindView(R.id.project_ryc)
    RecyclerView projectRyc;
    @BindView(R.id.parts)
    IconViewTextView parts;
    @BindView(R.id.parts_ryc)
    RecyclerView partsRyc;
    @BindView(R.id.other_pay)
    IconViewTextView otherPay;
    @BindView(R.id.other_ryc)
    RecyclerView otherRyc;
    @BindView(R.id.expend_ll)
    LinearLayout expendLl;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.open)
    ImageView open;
    @BindView(R.id.open_ll)
    FrameLayout openLl;
    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.close_ll)
    FrameLayout closeLl;
    private LoadingDialog loadingDialog;
    private String id;
    private WorkFormDetails.ReturnObjectBean workDetails;

    private ArrayList<NewPartsList.ResultListBean.PartsQualityListBean> selectList = new ArrayList<>();

    private ArrayList<Project> selectProjectList = new ArrayList<>();

    private ArrayList<ByPartsList.ResultListBean> selectByPartsList = new ArrayList<>();

    private List<CostType> costTypeList = new ArrayList<>();

    private FixingPartsAdapter fixPartsAdapter;

    private FixingProjectAdapter fixProjectAdapter;

    private FixingOtherPayAdapter costListAdater;
    private String code = "";
    private int formType;

    @Override
    protected int getContentView() {
        return R.layout.state_qualified;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        intRyc();

        loadingDialog.show();
        id = getIntent().getStringExtra("id");
        AppApi.workFormDetails(id, this, 0, this);
    }

    private void intRyc() {
        partsRyc.setLayoutManager(new LinearLayoutManager(mContext));
        fixPartsAdapter = new FixingPartsAdapter(R.layout.item_fixing_part, selectList);
        partsRyc.setAdapter(fixPartsAdapter);

        projectRyc.setLayoutManager(new LinearLayoutManager(mContext));
        fixProjectAdapter = new FixingProjectAdapter(R.layout.item_fixing_project, selectProjectList);
        projectRyc.setAdapter(fixProjectAdapter);

        otherRyc.setLayoutManager(new LinearLayoutManager(mContext));
        costListAdater = new FixingOtherPayAdapter(R.layout.item_fixing_other_pay, costTypeList);
        otherRyc.setAdapter(costListAdater);


        partsRyc.setHasFixedSize(true);
        partsRyc.setNestedScrollingEnabled(false);

        projectRyc.setHasFixedSize(true);
        projectRyc.setNestedScrollingEnabled(false);

        otherRyc.setHasFixedSize(true);
        otherRyc.setNestedScrollingEnabled(false);
    }


    @OnClick({R.id.back, R.id.close_ll, R.id.open_ll, R.id.share,R.id.phone_icon})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.close_ll:
                expendLl.setVisibility(View.GONE);
                closeLl.setVisibility(View.GONE);
                open.setVisibility(View.VISIBLE);
                break;
            case R.id.open_ll:
                expendLl.setVisibility(View.VISIBLE);
                closeLl.setVisibility(View.VISIBLE);
                open.setVisibility(View.GONE);
                break;
            case R.id.share:
                break;
            case R.id.phone_icon:
                StateQualifiedActivityPermissionsDispatcher.startCallWithPermissionCheck(StateQualifiedActivity.this);
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                WorkFormDetails workFormDetails = JSON.parseObject(result, WorkFormDetails.class);
                code = workFormDetails.getReturnObject().getCode();
                formType = Integer.parseInt(workFormDetails.getReturnObject().getType());
                orderNum.setText(code);
                tvTotal.setText("￥" + workFormDetails.getReturnObject().getTotalPrice());
                carNum.setText(workFormDetails.getReturnObject().getCarNumber());
                tvPhone.setText(workFormDetails.getReturnObject().getPhone());
                carType.setText(workFormDetails.getReturnObject().getCarName());
                tvOwner.setText(workFormDetails.getReturnObject().getCustomName());
                inTime.setText(workFormDetails.getReturnObject().getInTime());
                fixType.setText(workFormDetails.getReturnObject().getRepairName());
                mainPep.setText(workFormDetails.getReturnObject().getMainName());
                techPep.setText(workFormDetails.getReturnObject().getTecName());
                repairTips.setText(workFormDetails.getReturnObject().getRepairTips());

                selectProjectList.clear();
                selectList.clear();
                costTypeList.clear();

                List<WorkFormDetails.ReturnObjectBean.RepairOrderDetailListBean> dataBeanList = workFormDetails.getReturnObject().getRepairOrderDetailList();
                for (WorkFormDetails.ReturnObjectBean.RepairOrderDetailListBean detailListBean : dataBeanList) {
                    switch (detailListBean.getType()) {
                        case 1:
                            Project project = new Project();
                            project.setSelect(true);
                            project.setId(detailListBean.getRepairProId());
                            project.setAfterCutPrice(detailListBean.getOtherPrice());
                            project.setProjectName(detailListBean.getProject_name());
                            selectProjectList.add(project);
                            break;
                        case 2:
                            NewPartsList.ResultListBean.PartsQualityListBean parts = new NewPartsList.ResultListBean.PartsQualityListBean();
                            parts.setWantCount(detailListBean.getNum());
                            parts.setEditPrice(detailListBean.getOtherPrice());
                            parts.setCarWarehousePartsId(detailListBean.getPartId());
                            parts.setPartsName(detailListBean.getPartName());
                            parts.setPartsOeCode(detailListBean.getGoodsCode());
                            selectList.add(parts);
                            break;
                        case 3:
                            CostType costType = new CostType();
                            costType.setRemark(detailListBean.getOtherRemark());
                            costType.setCostName(detailListBean.getOtherName());
                            costType.setCost(String.valueOf(detailListBean.getOtherCost()));
                            costType.setPrice(String.valueOf(detailListBean.getOtherPrice()));
                            costTypeList.add(costType);
                            break;
                    }
                }
                fixProjectAdapter.notifyDataSetChanged();
                fixPartsAdapter.notifyDataSetChanged();
                costListAdater.notifyDataSetChanged();
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void startCall() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + tvPhone.getText().toString());
        intent.setData(data);
        startActivity(intent);
    }

    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showRationaleForPhone(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("源圈需要使用您的电话！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showDeniedForPhone() {
        SnackUtils.showError(mRootView, "您拒绝了电话权限！");
    }


    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showNeverAskForPhone() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止app使用您的电话,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        StateQualifiedActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
